<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use SimpleXMLElement;

class FmwJdPrintingController extends Controller
{
    protected $baseUrl = '/api/jd-printing/';

    protected $requestData = [];

    public function index(Request $request)
    {
        $method = str_replace($this->baseUrl, '', $request->getRequestUri());
        if (strpos($method, '?')) {
            $method = substr($method, 0, strpos($method, '?'));
        }

        if (!method_exists($this, $method)) {
            echo sprintf("[%s] mock function not exists", $method);
            exit;
        }

        return $this->$method($request);
    }

    public function fushidownload(Request $request)
    {
        $order_data = [
            'orderId' => '292108094505',
            'userName' => '丛……',
            'phone' => '1580xxxx',
            'address' => '北京海淀区……',
            'province' => '1',
            'city' => '2800',
            'county' => '55811',
            'images' => [],
        ];

        return $this->arrayToXml('order', $order_data);
    }

    function arrayToXml($root, $array)
    {
        $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><' . $root . '/>');
        $this->_arrayToXml($array, $xml, $root);
        return $xml->asXML();
    }

    function _arrayToXml($array, &$xml, $last_key)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $is_all_int = true;
                foreach (array_keys($value) as $k) {
                    if (!is_int($k)) {
                        $is_all_int = false;
                        break;
                    }
                }
                if ($is_all_int) {
                    $this->_arrayToXml($value, $xml, $key);
                } else {
                    $i_xml = is_int($key) ? $xml->addChild($last_key) : $xml->addChild($key);
                    $this->_arrayToXml($value, $i_xml, $key);
                }
            } else {
                $xml->addChild($key, $value);
            }
        }
    }
}